package org.example.pcbcircuitboard.controller;

import org.example.pcbcircuitboard.entity.SSEConnectEntity;
import org.example.pcbcircuitboard.pojo.ReceptionPojo;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;

/**
 * 创建SSE连接、数据推送到客户端 接口
 */
@RestController
@RequestMapping("/mqtt-sse")
@EnableScheduling
public class MqttSSEController {
    /**
     * 获取页面 SSE 连接
     * @return SseEmitter连接对象
     */
    @GetMapping("/left-top-data")
    public SseEmitter leftTopData() {
        SseEmitter emitter = new SseEmitter(Long.MAX_VALUE);
        emitter.onCompletion(() -> {
            SSEConnectEntity.removeEmitterConnection(SSEConnectEntity.leftTopUserId);
        });
        emitter.onTimeout(() -> {
            SSEConnectEntity.removeEmitterConnection(SSEConnectEntity.leftTopUserId);
        });
        emitter.onError(error -> {
            SSEConnectEntity.removeEmitterConnection(SSEConnectEntity.leftTopUserId);
        });
        SSEConnectEntity.addEmitterConnection(SSEConnectEntity.leftTopUserId, emitter);
        return emitter;
    }
    @Scheduled(fixedDelay = 3000)
    public void  sendSSEHeartbeat() throws IOException {
        for (SseEmitter emitter : SSEConnectEntity.emitters.values()){
            ReceptionPojo receptionPojo = new ReceptionPojo();
            receptionPojo.setStatus(1);
            emitter.send(receptionPojo);
        }
    }
}